//
//  UnviersalTool.m
//  Universal tool
//
//  Created by Fuhao on 16/4/7.
//  Copyright © 2016年 Fuhao. All rights reserved.
//

#import "UnviersalTool.h"
@implementation UnviersalTool
{
    UIAlertView * _atalert;
    NSString *_appid;
}

#pragma  mark 检查更新／更新
-(void)Checkversion:(NSString *)appid
{
    //获取当前版本
    _appid = appid;
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    CFShow((__bridge CFTypeRef)(infoDictionary));
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    //获得当前最新版本（从appstroe）
    NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@",appid ]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
    [request setHTTPMethod:@"POST"];
     NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
     ^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
         if(connectionError||data == nil)
         {
             [[UIApplication sharedApplication].keyWindow makeToast:@"连接失败"];
         }
         else{
             NSError *error = nil;
             NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error][@"results"];
             if(error)
             {
                 NSLog(@"失败");
             }
             NSDictionary *dict = [array lastObject];
             if(![app_Version isEqualToString:dict[@"version"]])
             {
                 if( [[[UIDevice currentDevice] systemVersion] floatValue] < 8.0)
                 {
                     _atalert = [[UIAlertView alloc]init];
                     _atalert.delegate = self;
                     _atalert.title = @"提示";
                     _atalert.message =@"检测到新版本，请立即更新序";
                     [_atalert addButtonWithTitle:@"稍后再说"];
                     [_atalert addButtonWithTitle:@"立即更新"];
                     
                     
                     [_atalert show];
                     
                 }
                 else{
                     UIAlertController *alter =[UIAlertController alertControllerWithTitle:@"提示" message:@"检测到新版本，请立即更新程序" preferredStyle:UIAlertControllerStyleAlert];
                     UIAlertAction *cencle = [UIAlertAction actionWithTitle:@"稍后再说" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                         return;
                     }];
                     UIAlertAction *ok = [UIAlertAction actionWithTitle:@"立即更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/cn/app/id%@?mt=8",appid]]];
                         
                     }];
                     [alter addAction:cencle];
                     [alter addAction:ok];
                     UIApplication *application = [UIApplication sharedApplication];
                     [application.keyWindow.rootViewController presentViewController:alter animated:YES completion:nil];
                 }

         }
         }
     }];
    

    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex ==1 && alertView == _atalert)
    {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/cn/app/id%@?mt=8",_appid]]];
    }
}

#pragma mark 获取视图的控制器
+(UIViewController *)Findviewscontroller:(UIView *)view
{

    for (UIView* next = [view superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}
+(UIImage*)createImageWithColor:(UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
@end
